package com.css.zfzx.fxpg.modules.surveyspot.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.zfzx.fxpg.common.utils.BeanUtil;
import com.css.zfzx.fxpg.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.fxpg.modules.citycounty.repository.FxCityCountyNativeRepository;
import com.css.zfzx.fxpg.modules.citycounty.repository.FxCityCountyRepository;
import com.css.zfzx.fxpg.modules.citycounty.repository.entity.FxCityCountyEntity;
import com.css.zfzx.fxpg.modules.citycounty.viewobjects.FxCityCountyQueryParams;
import com.css.zfzx.fxpg.modules.citycounty.viewobjects.FxCityCountyVO;
import com.css.zfzx.fxpg.modules.surveyspot.repository.FxSurveySpotNativeRepository;
import com.css.zfzx.fxpg.modules.surveyspot.repository.FxSurveySpotRepository;
import com.css.zfzx.fxpg.modules.surveyspot.repository.entity.FxSurveySpotEntity;
import com.css.zfzx.fxpg.modules.surveyspot.service.FxSurveySpotService;
import com.css.zfzx.fxpg.modules.surveyspot.viewobjects.FxSurveySpotQueryParams;
import com.css.zfzx.fxpg.modules.surveyspot.viewobjects.FxSurveySpotVO;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.fxpg.modules.workarea.repository.entity.FxWorkareaEntity;
import com.css.zfzx.fxpg.modules.workarea.viewobjects.FxWorkareaQueryParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author leon
 * @date 2020-11-27
 */
@Service
@Slf4j
public class FxSurveySpotServiceImpl implements FxSurveySpotService {

    @Autowired
    private FxSurveySpotRepository fxSurveySpotRepository;
    @Autowired
    private FxSurveySpotNativeRepository fxSurveySpotNativeRepository;
    /**
     * 市县数据仓库
     */
    @Autowired
    private FxCityCountyNativeRepository fxCityCountyNativeRepository;


    @Override
    public JSONObject queryFxSurveySpots(FxSurveySpotQueryParams queryParams, int curPage, int pageSize) {
        Page<FxSurveySpotEntity> fxSurveySpotPage = this.fxSurveySpotNativeRepository.queryFxSurveySpots(queryParams, curPage, pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(fxSurveySpotPage);
        return jsonObject;
    }


    @Override
    public FxSurveySpotEntity getFxSurveySpot(String id) {
        FxSurveySpotEntity fxSurveySpot = this.fxSurveySpotRepository.findById(id).orElse(null);
        return fxSurveySpot;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FxSurveySpotEntity saveFxSurveySpot(FxSurveySpotEntity fxSurveySpot) {
        String uuid = UUIDGenerator.getUUID();
        fxSurveySpot.setId(uuid);
        fxSurveySpot.setCreateUser(PlatformSessionUtils.getUserId());
        fxSurveySpot.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        this.fxSurveySpotRepository.save(fxSurveySpot);
        return fxSurveySpot;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FxSurveySpotEntity updateFxSurveySpot(FxSurveySpotEntity fxSurveySpot) {
        fxSurveySpot.setUpdateUser(PlatformSessionUtils.getUserId());
        fxSurveySpot.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        String id = fxSurveySpot.getId();
        FxSurveySpotEntity one = fxSurveySpotRepository.findById(id).get();
        BeanUtil.copyPropertiesIgnoreNull(fxSurveySpot, one);
        this.fxSurveySpotRepository.save(fxSurveySpot);
        return fxSurveySpot;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteFxSurveySpots(List<String> ids) {
        List<FxSurveySpotEntity> fxSurveySpotList = this.fxSurveySpotRepository.findAllById(ids);
        if (!PlatformObjectUtils.isEmpty(fxSurveySpotList) && fxSurveySpotList.size() > 0) {
            for (FxSurveySpotEntity fxSurveySpot : fxSurveySpotList) {
                this.fxSurveySpotRepository.delete(fxSurveySpot);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public String importExcel(MultipartFile file) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置解析从第1+1+1行开始
            params.setTitleRows(1);
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<FxSurveySpotVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), FxSurveySpotVO.class, params);
            List<FxSurveySpotVO> list = result.getList();
            // 批量新增
            List<Integer> errorlist = this.saveExcel(list);
            int errorSize = errorlist.size();
            returnMsg.append("成功导入" + (result.getList().size() - errorSize) + "条，失败" + (result.getFailList().size() + errorSize) + "条<br/>");
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<FxSurveySpotVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    FxSurveySpotVO vo = iterator.next();
                    String error = "";
                    returnMsg.append("第" + vo.getRowNum() + "行" + vo.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            for (Integer i : errorlist) {
                returnMsg.append("第" + i + "行" + "市县名称不存在,请先在市县数据管理中添加市县名称!<br/>");
            }
            return returnMsg.toString();
        } catch (RuntimeException e) {
            log.error(e.getMessage(), e);
            return e.getMessage();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            if ("库中该数据最多一条，请管理员清理数据库冗余数据！".equals(e.getMessage())) {
                return e.getMessage();
            } else {
                return "导入失败，请检查数据正确性";
            }
        }
    }

    /**
     * Excel新增
     *
     * @param list
     */
    private List<Integer> saveExcel(List<FxSurveySpotVO> list) {
        ArrayList<Integer> errolist = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            FxSurveySpotEntity entity = new FxSurveySpotEntity();
            FxSurveySpotVO vo = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(vo, entity);
            String errorMessage = saveOrUpdateFxSurveySpot(entity);
            if (errorMessage.contains("市县名称不存在")) {
                errolist.add(i + 1);
            }
        }
        return errolist;
    }

    private String saveOrUpdateFxSurveySpot(FxSurveySpotEntity entity) {
        String message = "OK";
        // 市县名称
        String cityCountyName = entity.getCityCountyName();
        FxCityCountyQueryParams cityCountyQueryParams = new FxCityCountyQueryParams();
        cityCountyQueryParams.setCityCountyName(cityCountyName);
        List<FxCityCountyEntity> fxCityCountyEntities = fxCityCountyNativeRepository.listFxCityCountys(cityCountyQueryParams);
        if (CollectionUtils.isEmpty(fxCityCountyEntities)) {
            message = "市县名称不存在,请先添加市县名称!";
        } else {
            // 调查点名称
            String surveySpotName = entity.getSurveySpotName();
            FxSurveySpotQueryParams spotQueryParams = new FxSurveySpotQueryParams();
            spotQueryParams.setCityCountyName(cityCountyName);
            spotQueryParams.setSurveySpotName(surveySpotName);
            List<FxSurveySpotEntity> surveySpotEntities = fxSurveySpotNativeRepository.listFxSurveySpots(spotQueryParams);
            if (CollectionUtils.isEmpty(surveySpotEntities)) {
                // 新增
                this.saveFxSurveySpot(entity);
            } else {
                // 修改
                if (surveySpotEntities.size() == 1) {
                    FxSurveySpotEntity surveySpotEntity = surveySpotEntities.get(0);
                    BeanUtil.copyPropertiesIgnoreNull(entity, surveySpotEntity);
                    this.updateFxSurveySpot(surveySpotEntity);
                } else {
                    throw new RuntimeException("库中该数据最多一条，请管理员清理数据库冗余数据！");
                }
            }
        }
        return message;
    }

    @Override
    public String exportExcel(FxSurveySpotQueryParams queryParams, HttpServletResponse response) {
        try {
            List<FxSurveySpotEntity> entities = fxSurveySpotNativeRepository.listFxSurveySpots(queryParams);
            // 深拷贝
            ArrayList<FxSurveySpotVO> vos = new ArrayList<>();
            for (FxSurveySpotEntity entity : entities) {
                FxSurveySpotVO vo = new FxSurveySpotVO();
                BeanUtils.copyProperties(entity, vo);
                vos.add(vo);
            }
            // 导出
            EasyPoiExcelUtil.exportExcel(vos, "调查点数据统计", "调查点数据", FxSurveySpotVO.class, "调查点数据.xlsx", response);
            return "导出成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    @Override
    public List<FxSurveySpotEntity> queryFxSurveySpotsForStatistic(FxSurveySpotQueryParams queryParams) {
        List<FxSurveySpotEntity> fxSurveySpots = this.fxSurveySpotNativeRepository.listFxSurveySpotsByYears(queryParams);
        return fxSurveySpots;
    }

    @Override
    public List<FxSurveySpotEntity> getFxSurveySpots(FxSurveySpotQueryParams queryParams) {
        List<FxSurveySpotEntity> fxSurveySpots = this.fxSurveySpotNativeRepository.listFxSurveySpots(queryParams);
        return fxSurveySpots;
    }

    @Override
    public String judgeRational(FxSurveySpotEntity fxSurveySpot) {
        String message = "OK";
        // 市县名称
        String cityCountyName = fxSurveySpot.getCityCountyName();
        FxCityCountyQueryParams cityCountyQueryParams = new FxCityCountyQueryParams();
        cityCountyQueryParams.setCityCountyName(cityCountyName);
        List<FxCityCountyEntity> fxCityCountyEntities = fxCityCountyNativeRepository.listFxCityCountys(cityCountyQueryParams);
        if (CollectionUtils.isEmpty(fxCityCountyEntities)) {
            message = "市县名称不存在,请先在市县数据管理中添加市县名称!";
        } else {
            // 调查点名称
            String surveySpotName = fxSurveySpot.getSurveySpotName();
            FxSurveySpotQueryParams spotQueryParams = new FxSurveySpotQueryParams();
            spotQueryParams.setCityCountyName(cityCountyName);
            spotQueryParams.setSurveySpotName(surveySpotName);
            List<FxSurveySpotEntity> surveySpotEntities = fxSurveySpotNativeRepository.listFxSurveySpots(spotQueryParams);
            if (CollectionUtils.isNotEmpty(surveySpotEntities)) {
                message = "该市县名称:" + cityCountyName + "下的调查点为" + surveySpotName + "的数据已存在！";
            }
        }
        return message;
    }

    @Override
    public List<String> getSurveySpotNames() {
        List<String> surveySpotNames = fxSurveySpotRepository.findSurveySpotNames();
        return surveySpotNames;
    }
}
